<template>
  <div id="app">
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <el-button type="primary"  @click="showAddForm">角色添加菜单</el-button>
        <el-button type="primary" @click="openAddMenu">添加菜单</el-button>
        <el-button type="primary" @click="openMenuDialog">菜单信息</el-button>
      </div>
      <el-tabs v-model="activeTab" @tab-click="onTabClick">
        <el-tab-pane
            v-for="roleMenu in roleMenus"
            :key="roleMenu.roleId"
            :label="roleMenu.roleName"
            :name="roleMenu.roleId.toString()"
        >
          <el-tree
              :data="roleMenu.menus"
              :props="defaultProps"
              node-key="id"
              :expand-on-click-node="false"
              @node-click="handleNodeClick"
              ref="menuTreeRef"
          >
            <template #default="{ node, data }">
              <span class="custom-tree-node">
                {{ node.label }}
              </span>
              <el-button size="small" type="danger" plain @click.stop="removeMenu(data)">删除</el-button>
            </template>
          </el-tree>
        </el-tab-pane>
      </el-tabs>

      <el-dialog v-model="dialogVisible" :title="dialogTitle" width="50%">
        <el-form :model="roleMenuForm" :rules="rules" ref="formRef" label-width="120px">

          <el-form-item label="角色名称" prop="roleName">
            <el-input v-model="roleMenuForm.roleName" disabled></el-input>
          </el-form-item>

          <el-form-item label="菜单名称" prop="parentMenuId">
            <el-cascader
                v-model="roleMenuForm.menuIds"
                :options="menus"
                :props="cascaderProps1"
                clearable
                @change="onParentChange"
            ></el-cascader>
          </el-form-item>
        </el-form>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="cancelRoleMenu">取 消</el-button>
            <el-button type="primary" @click="saveMenu">确 定</el-button>
          </span>
        </template>
      </el-dialog>


<!--      新增菜单对话框-->
      <el-dialog v-model="addVisible" :title="Title" width="50%">
        <el-form :model="menuForm"  ref="menuFormRef" label-width="120px">
          <el-form-item label="菜单名称" prop="name">
            <el-input v-model="menuForm.name" ></el-input>
          </el-form-item>
          <el-form-item label="菜单url" prop="url">
            <el-input v-model="menuForm.url" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item label="菜单图标" prop="icon">
            <el-input v-model="menuForm.icon" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item label="菜单类型" prop="type">
            <el-radio-group v-model="menuForm.type">
              <el-radio :label="'group'">顶层菜单</el-radio>
              <el-radio :label="'page'">子菜单</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="父级菜单" prop="pid">
            <el-cascader
                v-model="menuForm.pid"
                :options="menus"
                :props="cascaderProps"
                clearable
                @change="onParentChange"
            ></el-cascader>
          </el-form-item>
        </el-form>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="cancelAddMenu">取 消</el-button>
            <el-button type="primary" @click="save">确 定</el-button>
          </span>
        </template>
      </el-dialog>
<!--      菜单信息对话框-->
      <el-dialog v-model="menuVisible" title="菜单信息" width="50%">
        <el-tree
            :data="menus"
            :props="defaultProps"
            node-key="id"
            :expand-on-click-node="false"
            @node-click="handleNodeClick"
            ref="menuTreeRef"
        >
          <template #default="{ node, data }">
              <span class="custom-tree-node">
                {{ node.label }}
              </span>
            <el-button size="small" type="primary" plain @click.stop="edit(data)">编辑</el-button>
            <el-button size="small" type="danger" plain @click.stop="remove(data)">删除</el-button>
          </template>
        </el-tree>
      </el-dialog>

    </el-card>
  </div>
</template>

<script setup lang="ts">
import {ref, reactive, computed, watch, onMounted} from 'vue';
import axios from "../../http/axios";
import {ElMessage} from "element-plus";
//菜单相关
const addVisible = ref(false);
const menuForm = ref({
  id: undefined,
  name: '',
  url: '',
  pid: undefined,
  type: '',
  icon: ''
});
const openAddMenu = () => {
  Title.value = '添加菜单';
  addVisible.value = true;
};
const cancelRoleMenu = () => {
  dialogVisible.value = false
  menuForm.value = {
    id: undefined,
    name: '',
    url: '',
    pid: undefined,
    type: '',
    icon: ''
  };
};
const save = () => {
  //添加
  if (Title.value==="添加菜单"){
    axios.post("/sys/menu/add", menuForm.value).then((response)=>{
      if (response.data.code === 200) {
        ElMessage.success("添加成功");
        addVisible.value = false;
        menuForm.value = {
          id: undefined,
          name: '',
          url: '',
          pid: undefined,
          type: '',
          icon: ''
        };
      } else {
        ElMessage.error(response.data.message);
      }
    })
  }else if (Title.value==="编辑菜单"){
    axios.post("/sys/menu/update", menuForm.value).then((response)=>{
      if (response.data.code === 200) {
        ElMessage.success("编辑成功");
        addVisible.value = false;
        menuForm.value = {
          id: undefined,
          name: '',
          url: '',
          pid: undefined,
          type: '',
          icon: ''
        };
      } else {
        ElMessage.error(response.data.message);
      }
    })
}
}
const remove = (data) => {
  axios.delete("/sys/menu/delete/"+data.id).then((response)=>{
    if (response.data.code === 200) {
      ElMessage.success("删除成功");
      getAllMenus();
    } else if (response.data.code === 201){
      ElMessage.warning(response.data.message)
    }else {
      ElMessage.error(response.data.message);
    }
  })
}
const Title= ref('');
//获取所有菜单
const getAllMenus = () => {
  axios.get("/sys/menu/listAll").then((response)=>{
    if (response.data.code === 200) {
     menus.value = response.data.data;
    }
  })
};
interface Menu {
  id: number;
  name: string;
  pid?: number;
  children?: Menu[];
}
const menus = ref([]);
interface Role {
  roleId: number;
  roleName: string;
  menus: Menu[];
}
const openMenuDialog = () => {
  getAllMenus();
  menuVisible.value = true;
};
const roleMenus = ref<Role[]>([
  {
    roleId: 1,
    roleName: '',
    menus: []
  },
]);
const edit=(data) => {
  Title.value = '编辑菜单';
  addVisible.value = true;
  getAllMenus();
  menuForm.value = data;
};
const menuVisible= ref(false);
const activeTab = ref(roleMenus.value[0].roleId.toString());

const defaultProps = {
  id: 'id',
  children: 'children',
  label: 'name'
};
const cancelAddMenu=() => {
  addVisible.value = false;
  menuForm.value = {
    id: undefined,
    name: '',
    url: '',
    pid: undefined,
    type: '',
    icon: ''
  };
};
const dialogVisible = ref(false);

const roleMenuForm = reactive({
  id: undefined,
  name: '',
  pid: undefined,
  menuIds: [],
  roleId: undefined,
  roleName: ''
});
const resetRoleMenuForm = () => {
  roleMenuForm.id = undefined;
  roleMenuForm.roleId = undefined;
  roleMenuForm.roleName = '';
  roleMenuForm.name = '';
  roleMenuForm.pid = undefined;
  roleMenuForm.menuIds = [];
};

const dialogTitle = ref('添加菜单');

const formRef = ref();

const rules = reactive({
  menuName: [{ required: true, message: '请输入菜单名称', trigger: 'blur' }],
  parentMenuId: [{ required: true, message: '请选择父级菜单', trigger: 'blur' }]
});

const cascaderProps1 = {
  value: 'id',
  label: 'name',
  children: 'children',
  multiple: true,
  expandTrigger: 'click', // 或者 'click'
};
const cascaderProps = {
  value: 'id',
  label: 'name',
  children: 'children',
  checkStrictly: true, // 如果你想严格控制父子级不能同时被选中，设为 true；否则设为 false
  expandTrigger: 'click', // 或者 'click'
  emitPath: false // 设置为 false 允许选择任意层级
};
const showAddForm = () => {
  dialogVisible.value = true;
  dialogTitle.value = '角色添加菜单';
  roleMenuForm.name = '';
  roleMenuForm.pid = undefined;
  //将角色id 赋值给表单
  roleMenuForm.roleId = parseInt(activeTab.value);
  roleMenuForm.roleName = roleMenus.value.find(role => role.roleId === parseInt(activeTab.value)).roleName;
};

const handleNodeClick = (data: Menu) => {
  console.log(`Clicked: ${data.name}`);
};

const removeMenu = (menu) => {
  axios.get('/sys/menu/deleteRoleMenu/'+activeTab.value+"/"+menu.id).then(response => {
    if (response.data.code === 200){
      ElMessage.success('删除成功');
      getMenus();
    }else {
      ElMessage.error(response.data.message);
    }
  })
};

const onParentChange = (value: any) => {
  roleMenuForm.pid = value ? value[value.length - 1] : undefined;
};

const saveMenu = () => {
  //处理数据
  const uniqueElements = new Set();
  roleMenuForm.menuIds.forEach(array => {
    array.forEach(element => {
      uniqueElements.add(element);
    });
  });
  const menuIds = Array.from(uniqueElements);
  console.log(menuIds)

  axios.post('/sys/menu/addRoleMenu/'+roleMenuForm.roleId,menuIds).then(response => {
    if (response.data.code === 200){
      ElMessage.success('添加成功');
      roleMenuForm.menuIds = [];
      dialogVisible.value = false;
      getMenus();
    }else if (response.data.code === 201){
      ElMessage.info(response.data.message);
    } else {
      ElMessage.error(response.data.message);
    }
  })
};

const onTabClick = (tab: any) => {
  activeTab.value = tab.name;
};
//查询菜单
const getMenus =() => {
  axios.get('/sys/menu/list').then(response => {
    if (response.data.code === 200){
      roleMenus.value = response.data.data;
    }else {
      ElMessage.error(response.data.msg);
    }
})
};
onMounted(() => {
  getMenus();
  getAllMenus();
});
</script>

<style scoped>
#app {
  padding: 20px;
}

.box-card {
  margin-bottom: 20px;
}

.custom-tree-node {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: 14px;
  padding-right: 8px;
}

.clearfix .el-card__header {
  padding: 0 20px;
  height: 40px;
  line-height: 40px;
}

.clearfix .el-card__body {
  padding: 20px;
}
/* Ensure styles apply to el-dialog */
:deep(.el-dialog) {
  position: fixed !important;
  top: 50% !important;
  left: 50% !important;
  transform: translate(-50%, -50%) !important;
  max-width: 90% !important;
  max-height: 80vh !important;
}

/* Center the dialog body content */
:deep(.el-dialog__body) {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
}

/* Ensure the dialog header is centered */
:deep(.el-dialog__header) {
  text-align: center;
}

:deep(.el-dialog__body .el-form) {
  width: 100%;
}

:deep(.el-dialog__body .el-form-item) {
  margin-bottom: 20px; /* Adjust space between form items */
}

</style>